<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\model\Menu;
use app\model\Role;
use tauthz\facade\Enforcer;
use think\facade\Validate;
use think\response\Json;

class AdminRole extends AdminBase
{

	protected $middleware = [
        'app\middleware\AdminLogin',
		'app\middleware\AdminAuth' => ['except' => ['power'] ]
	];

	private string $menuName = '角色管理';

    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {
        $limit = input('pageSize/d',10);
        //分页配置
        $pageConfig = ['list_rows'=>$limit,'var_page'=>'pageNum'];

        //搜索字段配置
        $search = [
            [
                'label'=>'角色名称',//标签
                'prop'=> 'name',//表单名称
                'field' => 'name|alias|description',//查询字段
                'placeholder'=> '模糊搜索名称|别名|描述',
                'required'=> false,//是否必填
                'expression' => 'like',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
                'type'=> 'input',//类型：input,select,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 's',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
            ],
        ];
        $map = [];
        $this->setMap($search,$map);

		$data = Role::where($map)
            ->order('sort','asc')
			->paginate($pageConfig);

        $this->result['data'] = [
            'total' => $data->total(),
            'data' => $data->items(),
            'search' => $search
        ];

		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
     * 获取菜单权限
     * @throws
     * @return Json
     */
    public function power():Json
    {
        $data = Menu::where('parent_id',0)
            ->where('is_hide',0)
            ->order('sort','asc')
            ->select()->toArray();

        $this->nextList($data,'menu');
        $this->result['data'] = $data;
        return jJson($this->result);
    }

    /**
	 * 保存编辑的资源
	 * @throws
	 * @return Json
	 */
	public function save():Json
	{
		//获取form表单
		$param = input('param.',[]);
		$param = toUnderline($param);

        $model = new Role();
        $fields = $model->getFields();
        $pk = $model->getPk();
        $id = $param[$pk] ?? 0;

		try{
            $rule = [
                'alias' => 'require|max:32|unique:role,alias,'.$id.','.$pk,
                'name' => 'require|max:64',
                'description' => 'max:512',
                'power' => 'require|array|min:1'
            ];

            $message = [
                'alias.require' => '英文别名必填',
                'alias.max' => '英文别名最多32个字符',
                'alias.unique' => '英文别名已存在，请重新输入',
                'name.require' => '角色名必填',
                'name.max' => '角色名最多64个字符',
                'description' => '角色描述最多512个字符',
                'power.require' => '菜单权限必选',
                'power.array' => '菜单权限必须是数组',
                'power.min' => '菜单权限至少选择一项',
            ];
            $validate = Validate::rule($rule)->message($message);
            if(!$validate->check($param)){
                throw new \Exception($validate->getError());
            }

			if(!$id){
				//新增
				$model->create($param,$fields);
			}else{
				//修改
				$info = $model->find($id);
				if(!$info){
					throw new \Exception('无效参数');
				}
                unset($fields['alias']);
				$info->allowField($fields)->save($param);

                //删除所有权限
                Enforcer::deletePermissionsForUser('role_'.$param['alias']);
			}
            //获取权限菜单
            $menus = Menu::field('id,controller,power')->whereIn('id',$param['power'])->select()->toArray();
            if(count($menus)){
                foreach ($menus as $m){
                    if(!$m['controller'] || !$m['power']) continue;
                    Enforcer::addPermissionForUser('role_'.$param['alias'],strtolower($m['controller']),strtolower($m['power']));
                }
            }

		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}
		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}



    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        $id = input('id/d',0);

        $role = Role::find($id);
        if($role){
            $role->delete();

            //删除所有角色
            Enforcer::deleteRolesForUser('role_'.$role['name']);
        }

        $this->result['msg'] = '删除ID：'.$id;

        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }

}
